const app = getApp();
import { mediaPreView } from "../../utils/util";
import { baseUrl } from "../../api/request";
import { getStorage } from "../../utils/localStorage"
Component({
  properties: {
    //图片上传数量默认9张
    imgNum: {
      type: Number,
      value: 9,
    },
    value: {
      type: String,
      value: "",
      observer: function (val) {
        if (val) {
          let arr = val.split(",");
          this.setData({
            imageList: arr
          });
        };
      }
    }
  },
  data: {
    imgUrl: baseUrl,
    imageList: [],
    url: baseUrl + '/common/upload',
    uoloadImage: [],
  },
  lifetimes: {
    attached() { },
    detached() { },
  },
  methods: {
    //选择相册还是相机方法
    media() {
      wx.showActionSheet({
        itemList: ['相册', '相机'],
        success: res => {
          if (res.tapIndex === 0) {
            this.upload('相册');
          } else if (res.tapIndex === 1) {
            this.upload('相机');
          }
        },
        fail: err => {
          console.log('取消选择：打开相机或者相册', err);
        }
      })
    },
    //调用图片上传方法
    upload(val) {
      const sourceType = val === '相机' ? 'camera' : 'album';
      wx.chooseMedia({
        count: 9, //最多可以选择的图片张数
        mediaType: ['image'], //文件类型,image:图片，video:视频，mix:可同时选择图片和视频
        sizeType: ['compressed'], //所选的图片的尺寸,original:原图,compressed:压缩图  
        sourceType: [sourceType], //选择图片的来源:album:从相册选图,camera:使用相机
        success: res => {
          const { type, tempFiles } = res;
          let arr = this.data.imageList;
          tempFiles.forEach(item => {
            // console.log(item.tempFilePath, 'item.tempFilePath');
            arr.push(item.tempFilePath);
            this.compressImage(item.tempFilePath, 0.8, function ysRes(e) {
              console.log(e, '压缩图片');
            });
            this.uploadFile(item.tempFilePath);

            // if (item.size <= 2000000) {
            //     this.uploadFile(item.tempFilePath);
            // } else {
            //     wx.showToast({
            //         icon: 'none',
            //         title: '上传图片不能大于2M',
            //     });
            // }
          });
          this.setData({
            imageList: arr,
          });
        },
        fail: err => {
          console.log(err, '图片上传');
        }
      })
    },


    //上传图片到服务器
    uploadFile(file) {
      wx.uploadFile({
        filePath: file,
        name: "file",
        url: this.data.url,
        header: {
          "Content-Type": "multipart/form-data",
          "Authorization": "Bearer" + " " + getStorage('token')
        },
        formData: null,
        success: res => {
          const data = JSON.parse(res.data);
          let arr = this.data.uoloadImage;
          if (data.code === 200) {
            arr.push(data.fileName[0]);
            this.triggerEvent('myEvent', arr);
          };
        },
        fail: err => {
          wx.showToast({
            icon: 'none',
            title: '上传图片失败' + err.msg,
            duration: 1000,
          });
          setTimeout(() => {
            wx.hideLoading();
          }, 1200)
        }
      })
    },

    //图片预览
    privew(e) {
      const url = e.currentTarget.dataset.url;
      mediaPreView(url); //图片预览全局方法
    },

    //删除图片
    delete(e) {
      const index = e.currentTarget.dataset.index,
        arr = this.data.imageList.filter((item, i) => index != i);
      this.setData({
        imageList: arr,
      });
      this.triggerEvent('myEvent', this.data.imageList);
    },


    /* 
      *图片压缩
      *file 原始图片大小
      *callback 回调函数
  */
    compressImage(filePath, quality, callback) {
      wx.getImageInfo({
        src: filePath,
        success: function (res) {
          var canvasWidth = res.width;
          var canvasHeight = res.height;
          var ctx = wx.createCanvasContext('myCanvas');

          // 设置canvas的宽高与原图一致
          ctx.width = canvasWidth;
          ctx.height = canvasHeight;

          ctx.drawImage(filePath, 0, 0);
          console.log(22222);
          // 将canvas转换为图片文件
          ctx.draw(false, function () {
            console.log(11111);
            wx.canvasToTempFilePath({
              canvasId: 'myCanvas',
              fileType: 'jpg',
              quality: quality,
              success: function (res) {
                console.log(res.tempFilePath, '压缩图片res');
                callback(res.tempFilePath);
              },
              fail: function (err) {
                console.error(err);
                callback(null);
              }
            });
          });
        },
        fail: function (err) {
          console.error(err);
          callback(err);
        }
      });
    },


  }
})